package springboot.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import springboot.service.TuserService;
import springboot.utlis.FileUtils;

@SuppressWarnings("unused")
@Controller
public class FileController {
	@Autowired
	private TuserService tuserService;
	// 获取主机端口
	private String post;
	// 获取本机ip
	private String host;
	// 图片存放根路径
	private String rootPath = "D:";
	// 图片存放根目录下的子目录
	private String sonPath = "/EclipseProject/springboot/src/main/resources/static/upload/";
	// 获取图片链接
	private String imgPath;

	/**
	 * 上传文件
	 * 
	 * @param file
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = "multipart/form-data")
	@ResponseBody
	public Map<String, Object> upload(@RequestParam("file") MultipartFile file, HttpSession session) {
		Map<String, Object> map = new HashMap<>();
		try {
			String imgPath1 = FileUtils.UpLoadFile(file, rootPath + sonPath, map).get("filePath").toString();
		} catch (IllegalStateException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 返回上传的文件是否为空，即没有选择任何文件，或者所选文件没有内容。
		// 防止上传空文件导致奔溃
//		if (file.isEmpty()) {
//			map.put("success", false);
//			map.put("message", "文件为空");
//			return map;
//		}
		// 获取本机IP
//		try {
//			host = InetAddress.getLocalHost().getHostAddress();
//		} catch (UnknownHostException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		// 获取文件名
//		String fileName = file.getOriginalFilename();
		// 设置文件上传后的路径
//		String filePath = rootPath + sonPath;
		// 创建文件路径
//		File dest=new File(filePath+fileName);
//		String imgPath=("/upload/"+fileName).toString();
		// 检测是否存在目录
//		if (!dest.getParentFile().exists()) {
		// 如果不存在就创建
//			dest.getParentFile().mkdirs();
//		}
//		try {
		// transferTo（dest）方法将上传文件写到服务器上指定的文件
//			file.transferTo(dest);
		// 将连接保存到URL中
		if (tuserService.imgLocalhos(Integer.parseInt(session.getAttribute("id").toString()),
				"/upload/" + file.getOriginalFilename())) {
			map.put("success", true);
			map.put("message", imgPath);
		} else {
			map.put("success", false);
			map.put("message", "路径保存失败");
		}
//		} catch (IllegalStateException | IOException e) {
		// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		return map;
	}

	/**
	 * 下载文件
	 * @throws IOException 
	 */
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public void Download(HttpServletResponse res) throws IOException {
		String fileName = "0f4776b0ca17d959ff5fc16c55198746.mp4";
		FileUtils.downloadFile(res, fileName);
//		res.setHeader("content-type", "application/octet-stream");
//		res.setContentType("application/octet-stream");
//		res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
//		byte[] buff = new byte[1024];
//		BufferedInputStream bis = null;
//		OutputStream os = null;
//		try {
//			os = res.getOutputStream();
//			bis = new BufferedInputStream(new FileInputStream(new File(rootPath + sonPath + fileName)));
//			int i = bis.read(buff);
//			while (i != -1) {
//				os.write(buff, 0, buff.length);
//				os.flush();
//				i = bis.read(buff);
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		} finally {
//			if (bis != null) {
//				try {
//					bis.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//		}
	}
}
